package com.mvc.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.BussResp;
import com.mvc.model.WlInformation;
import com.mvc.model.WlStock;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.common.UtilTools;
@RestController
@RequestMapping("/interface")
public class InterfaceCtr {

	private SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");

	@RequestMapping("/test")
	@ResponseBody
	public BussResp test() throws IOException, InterruptedException {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("gb2312")));
		String html=UtilTools._POST("http://biz.finance.sina.com.cn/suggest/lookup_n.php?country=&q=A中").setTemplate(restTemplate).deal(String.class);
		Document doc = Jsoup.parse(html);
		Elements rs=doc.select("#hk_warrant").next("div").select("a");
		Iterator<Element> _data = rs.iterator();
		while (_data.hasNext()){
			Element e=_data.next();
			String str=e.html();
			str=str.replaceAll("</?[^>]+/?>","");
			System.out.println(str);
		}
		return null;
	}

	@RequestMapping("/queryWL")
	@ResponseBody
    public BussResp CTMexists(String name,String filtername) throws IOException, InterruptedException {
		List<WlInformation> data=new ArrayList<>(100);
//		String queryurl="http://searchapi.eastmoney.com/api/suggest/get?input="+name+"&type=14&token=D43BF722C8E33BDC906FB84D85E326E8&markettype=&mktnum=&jys=&classify=&securitytype=&count=9999999";
		String infurl="http://web.ifzq.gtimg.cn/appstock/app/HkWarrant/hkw?code=";
		String purl="http://qt.gtimg.cn/?q=s_hk";
//		System.out.println(queryurl);
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("gb2312")));
		String html=UtilTools._POST("http://biz.finance.sina.com.cn/suggest/lookup_n.php?country=&q="+name).setTemplate(restTemplate).deal(String.class);
		Document doc = Jsoup.parse(html);
		Elements rs=doc.select("#hk_warrant").next("div").select("a");
		Iterator<Element> _data = rs.iterator();

//		String result=UtilTools._POST(queryurl,UtilTools.getRequest()).get(String.class);
//		JSONArray edate=JSONObject.fromObject(result).getJSONObject("QuotationCodeTable").getJSONArray("Data");
//		Iterator<JSONObject> _data= edate.iterator();
		CountDownLatch ct=new CountDownLatch(rs.size()*2);
		while (_data.hasNext()){
			String[] ifa=_data.next().html().replaceAll("</?[^>]+/?>","").split(" ");
			WlInformation obj=new WlInformation();
			obj.code=ifa[0];
			obj.name=ifa[1];
			if(filtername!=null && obj.name.indexOf(filtername)==-1){
				ct.countDown();ct.countDown();
				continue;
			}
			data.add(obj);
			//信息获取
//			String j_inf=UtilTools._POST(infurl+obj.code).get(String.class);
//			String j_price=UtilTools._POST(purl+obj.code).get(String.class);

//			System.out.println(obj.code);
			UtilTools._POST(infurl+obj.code).syncget(new ParameterizedTypeReference<String>(){}, new ListenableFutureCallback<ResponseEntity<String>>(){

				@Override
				public void onSuccess(ResponseEntity<String> result) {

					try {
						String j_inf=result.getBody();
						JSONObject inf=JSONObject.fromObject(j_inf).getJSONObject("data");
						obj.type=inf.getString("xz");
						obj.lastTradeDate=sf.parse(inf.getString("zhjyr"));
						obj.lastDate=sf.parse(inf.getString("dqr"));
						obj.xqj= inf.has("xqj")?inf.getDouble("xqj"):inf.getDouble("xqjg");
						JSONObject stocks=inf.getJSONObject("stock");
						obj.stock=new WlStock();
						obj.stock.code=stocks.getString("stock_code");
						obj.stock.name=inf.getString("xgzc");
						obj.stock.xj=stocks.getDouble("stock_zxj");
						obj.stock.zf=stocks.getDouble("stock_zdf");
						obj.stock.afamt=stocks.getDouble("stock_zde");
						if(!inf.has("xqbl")){
							String blurl="http://web.sqt.gtimg.cn/q=r_hk"+obj.code;
							String istr=UtilTools._POST(blurl).get(String.class);
							String istrs[]=istr.split("~");
//							System.out.println();
							obj.xqbl=Double.valueOf(istrs[44]);
						}else obj.xqbl=inf.getDouble("xqbl");

//						obj.xqbl=inf.has("xqbl")?:-1;
						//http://web.sqt.gtimg.cn/q=r_hk68941
					} catch (ParseException e) {
						e.printStackTrace();
					} finally {
						ct.countDown();
//						System.out.println("A:"+ct.getCount());
					}
				}

				@Override
				public void onFailure(Throwable ex) {
					ex.printStackTrace();
					ct.countDown();
//					System.out.println("A:"+ct.getCount());
				}
			});


			UtilTools._POST(purl+obj.code).syncget(new ParameterizedTypeReference<String>(){}, new ListenableFutureCallback<ResponseEntity<String>>() {

				@Override
				public void onSuccess(ResponseEntity<String> result) {
					try {
						String j_price=result.getBody();
						String[] pstr=j_price.split("=")[1].replaceAll(Pattern.quote("\""),"").split(Pattern.quote("~"));
						obj.price=Double.parseDouble(pstr[3]);
						obj.zf=Double.parseDouble(pstr[5]);
						obj.afamt=Double.parseDouble(pstr[4]);

					} catch (NumberFormatException e) {
						e.printStackTrace();
					} finally {
						ct.countDown();
//						System.out.println("B:"+ct.getCount());
					}
				}

				@Override
				public void onFailure(Throwable ex) {
					ex.printStackTrace();
					ct.countDown();
//					System.out.println("B:"+ct.getCount());
				}
			});
		}
		ct.await();






		//行权比例
		data.sort((o1,o2)->{
			if(o1.xqbl!=null && o2.xqbl!=null)
				return o2.xqbl.compareTo(o1.xqbl);
			else
				return -1;
		});

		//底股排序
		data.sort((o1,o2)->{
			if(o1.stock!=null && o2.stock!=null)
				return o1.stock.code.equals(o2.stock.code)?0:1;
			else
				return  -1;
		});

		//行权价格排序
		data.sort((o1,o2)->{
			if(o1.xqj!=null && o2.xqj!=null)
				return o2.xqj.compareTo(o1.xqj);
			else
				return  -1;
		});

		//到期时间降序
		data.sort((o1,o2)->{
			if(o1.lastDate!=null && o2.lastDate!=null)
				return o2.lastDate.compareTo(o1.lastDate);
			else
				return  -1;
		});

		data.forEach(v->{
			try {
				if(v.xqj!=null){//溢价=底层股票现价-行权价-现价*行权比例
                    //认购证的溢价=（认股证现价×兑换比率+行使价－相关资产现价）/相关资产现价×100%
                    if(v.type!=null && (v.type.indexOf("认购")!=-1 || v.type.indexOf("牛")!=-1))
                        v.yj=new BigDecimal((v.price*v.xqbl+v.xqj-v.stock.xj)/v.stock.xj).setScale(2,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).doubleValue();

                    //认沽证的溢价=（认股证现价×兑换比率－行使价+相关资产现价）/相关资产现价×100%
                    else if(v.type!=null && (v.type.indexOf("沽")!=-1 || v.type.indexOf("熊")!=-1))
                        v.yj=new BigDecimal((v.price*v.xqbl-v.xqj+v.stock.xj)/v.stock.xj).setScale(2,BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).doubleValue();
    //				v.yj=new BigDecimal((v.stock.xj-v.xqj-v.price*v.xqbl)).setScale(2,BigDecimal.ROUND_DOWN).doubleValue();
                }
			} catch (Exception e) {
				e.printStackTrace();
			}
		});

		for (int i = 0; i < data.size(); i++) {
			if(i==0){
				data.get(i).classname="tableorow1";
//				continue;
			}
			WlInformation wl1=data.get(i);
			WlInformation wl2=data.get(i==data.size()-1?i:i+1);
			if(wl1.xqj!=null && wl2.xqj!=null && new BigDecimal(wl1.xqj/wl2.xqj).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue()==1D //行权价相近
				&& wl1.lastDate !=null && wl2.lastDate!=null && wl1.lastDate.getTime()-wl2.lastDate.getTime()<=864000000	//日期相差少于10天
					&& wl1.xqbl!=null && wl2.xqbl!=null && wl1.xqbl.intValue()==wl2.xqbl.intValue()//行权倍数一致
					&& wl1.stock!=null && wl2.stock!=null && wl1.stock.code.equals(wl2.stock.code)//底层股票一致
					){
				wl2.classname=wl1.classname;
			}else{
				if("tableorow1".equals(wl1.classname)) wl2.classname="tableorow2";
				else  wl2.classname="tableorow1";
			}
		}
		
		return BussResp.createResp(data);
    }
}
